/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package unilearn.dao.hibernate;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import unilearn.dao.PersonDAO;
import unilearn.vo.Person;

/**
 *
 * @author Yat
 */
public class PersonDAOImpl extends HibernateDAO implements PersonDAO {

    public PersonDAOImpl() {
        super();
    }

    public PersonDAOImpl(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

    @Override
    public void setSessionFactory(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    @Override
    public List<Person> getAll() throws Exception {
        return super.getAll(Person.class.getName());
    }

    @Override
    public Person get(int id) throws Exception {
        Session s = sessionFactory.openSession();
        Transaction t = s.beginTransaction();

        try {
            Query query = s.createQuery("from " + Person.class.getName() + " p where p.id = " + id);
//            System.out.println("from " + Person.class.getName() + " p where p.id = " + id);//***
            List<Person> ps = query.list();
            if ((ps == null) || (ps.isEmpty())) {
                return null;
            }
//            System.out.println("ps: " + ps.size());//***
            return ps.get(0);
        } finally {
            t.commit();
            s.close();
        }
    }

    @Override
    public List<Person> find(Person person) throws Exception {
        return (List<Person>) super.find(person);
    }

    @Override
    public Person insert(Person person) throws Exception {
        super.insert(person);
        return person;
    }

    @Override
    public Person update(Person person) throws Exception {
        super.update(person);
        return person;
    }

    @Override
    public void delete(Person person) throws Exception {
        super.delete(person);
    }
}
